package com.ygj.easemob.server.example.api.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ygj.easemob.server.example.api.ChatMessageAPI;
import com.ygj.easemob.server.example.api.EasemobRestAPI;
import com.ygj.easemob.server.example.comm.ClientContext;
import com.ygj.easemob.server.example.comm.MessageTemplate;
import com.ygj.easemob.server.example.comm.wrapper.QueryWrapper;
import com.ygj.easemob.server.example.comm.wrapper.ResponseWrapper;

public class EasemobChatMessage extends EasemobRestAPI implements ChatMessageAPI {

	private static final String ROOT_URI = "/chatmessages";

	@Override
	public Object exportChatMessages(Long limit, String cursor, String query) {
		String url = null;
		ResponseWrapper responseWrapper = new ResponseWrapper();
		try {
			url = getContext().getSeriveURL() + getResourceRootURI() + "?ql=" + URLEncoder.encode(query,"utf-8");
		} catch (UnsupportedEncodingException e1) {
			responseWrapper.addError(e1.getMessage());
//			e1.printStackTrace();
		}
		QueryWrapper queryWrapper = QueryWrapper.newInstance().addLimit(limit).addCursor(cursor).addQueryLang(query);
		// HeaderWrapper header = HeaderHelper.getDefaultHeaderWithToken();

		// Map map = new HashMap();
		// for(int i = 0; i < queryWrapper.getQueries().size(); i++){
		// map.put(queryWrapper.getQueries().get(i).getName(),
		// queryWrapper.getQueries().get(i).getValue());
		// }

		// System.out.println(HttpUtil.doPostSSL(url, map));
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet();
		BufferedReader in = null;
		String content = null; 
		try {
			request.setURI(new URI(url));
			ClientContext context = ClientContext.getInstance();
			request.setHeader("Authorization", "Bearer " + context.getAuthToken());
			request.setHeader("Content-Type", "application/json");
			HttpResponse response = client.execute(request);

			
			content = readResponse(responseWrapper, response, false).toString();
//			System.out.println(content);

		} catch (URISyntaxException e) {
			responseWrapper.addError(e.getMessage());
//			e.printStackTrace();
		} catch (ClientProtocolException e) {
			responseWrapper.addError(e.getMessage());
//			e.printStackTrace();
		} catch (IOException e) {
			responseWrapper.addError(e.getMessage());
//			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					responseWrapper.addError(e.getMessage());
//					e.printStackTrace();
				}
			}
			return content;
		}

//		return null;
		// return getInvoker().sendRequest(HTTPMethod.METHOD_GET, url, header,
		// null, queryWrapper);
	}

	@Override
	public String getResourceRootURI() {
		return ROOT_URI;
	}
	
	private ResponseWrapper readResponse(ResponseWrapper responseWrapper, HttpResponse response, boolean isFile) {
        ObjectNode responseNode;
        HttpEntity entity = response.getEntity();
        if( null != entity ) {
            responseWrapper.setResponseStatus(response.getStatusLine().getStatusCode());

            Object responseContent;
            try {
                if(isFile){
                    responseContent = entity.getContent();
                } else {
                    responseContent = EntityUtils.toString(entity, "UTF-8");
                    EntityUtils.consume(entity);
                }
            } catch (ParseException e){
                responseWrapper.addError(e.getMessage());
                return responseWrapper;
            } catch (IOException e) {
                responseWrapper.addError(e.getMessage());
                return responseWrapper;
            }

            if(!isFile) {
                ObjectMapper mapper = new ObjectMapper();
                JsonFactory factory = mapper.getFactory();
                JsonParser jp;
                try {
                    jp = factory.createParser(responseContent.toString());
                    responseNode = mapper.readTree(jp);
                    responseWrapper.setResponseBody(responseNode);
                } catch (IOException e) {
                    responseWrapper.addError(MessageTemplate.STR2JSON_ERROR_MSG);
                }
            } else {
                responseWrapper.setResponseBody(responseContent);
            }
        }
        return responseWrapper;
    }
}
